<template>
  <el-dialog
    v-if="openBoole"
    v-model="openBoole"
    :close-on-click-modal="false"
    custom-class="mydialog"
    width="800px"
    :title="title"
    @close="close"
  >
    <el-form
      ref="openRef"
      :model="formData"
      :rules="rules"
      label-width="140px"
      size="small"
    >
      <el-row gutter="40">
        <el-col :span="12">
          <el-form-item
            label="收款金额"
            prop="receiveAmount"
          >
            <el-input
              v-model="formData.receiveAmount"
              clearable
              placeholder="请输入收款金额"
              @input="formData.receiveAmount=formData.receiveAmount.replace(/^\.+|[^\d.]/g,'')"
            >
              <template #append>
                <span>元</span>
              </template>
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item
            label="付款方类型"
            prop="customerType"
          >
            <el-select
              v-model="formData.customerType"
              style="width: 100%"
              placeholder="请选择付款方类型"
              @change="customerTypeChange"
            >
              <el-option
                v-for="item in returnTypeOption"
                :key="item.id"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item
            label="付款方名称"
            prop="customerId"
          >
            <el-select
              v-model="formData.customerId"
              style="width:100%"
              filterable
              remote
              reserve-keyword
              placeholder="请输入关键词搜索"
              :remote-method="customerQuerySearch"
              :loading="customerLoading"
              @change="handleCustomerSelect"
            >
              <el-option
                v-for="(item) in customerOption"
                :key="item.id"
                :value="item.id"
                :label="getCustomerLabel(item)"
              >
                <div class="productName">
                  <span v-if="formData.customerType ==='agent'">{{ item.agentName }}</span>
                  <span v-if="formData.customerType ==='distribute'">{{ item.distributeName }}</span>
                  <span v-if="formData.customerType ==='terminal'">{{ item.terminalName }}</span>
                  <span v-if="formData.customerType ==='seller'">{{ item.sellerName }}</span>
                </div>
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item
            label="付款开户行"
            prop="bankName"
          >
            <el-input
              v-model="formData.bankName"
              clearable
              placeholder="请输入付款开户行"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item
            label="付款银行账号"
            prop="bankNumber"
          >
            <el-input
              v-model="formData.bankNumber"
              clearable
              placeholder="请输入付款银行账号"
              oninput="value=value.replace(/[^\d]/g,'')"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item
            label="付款日期"
            prop="payTime"
          >
            <date-picker
              v-model:date="formData.payTime"
              style="width: 100%"
              type="date"
              placeholder="选择日期"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item
            label="负责营销职员"
            prop="headId"
          >
            <el-select
              v-model="formData.headId"
              style="width: 100%"
              placeholder="请选择负责营销职员"
              @change="officeClerkChange"
            >
              <el-option
                v-for="item in officeClerkOption"
                :key="item.id"
                :label="item.realName"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item
            label="款项描述"
            prop="remark"
          >
            <el-input
              v-model="formData.remark"
              type="textarea"
              placeholder="请输入款项描述"
            />
          </el-form-item>
        </el-col>

      </el-row>
    </el-form>
    <template #footer>
      <div
        class="dialog-footer"
        style="display:flex;justify-content:center;align-items:center;"
      >
        <el-button
          class="border-btn"
          size="small"
          style="margin-right: 20px;"
          @click="close"
        >取消</el-button>
        <el-button
          class="main-btn"
          size="small"
          type="primary"
          @click="handlSubmit"
        >提交</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script>
import { getCurrentInstance, inject, reactive, toRefs } from 'vue'
import { crmStore } from '@CRM/store'

export default {
  name: 'ReturnedMoneyForm',
  emits: ['onSuccess'],
  setup(props, context) {
    const api = inject('api')
    const receiveAmountPass = (rule, value, callback) => {
      if (value) {
        if (value > 0) {
          reactiveData.formData.receiveAmount = Number(value)
          callback()
        } else {
          callback(new Error('收款金额必须大于0'))
        }
      } else {
        callback(new Error('请输入收款金额'))
      }
    }
    var reactiveData = reactive({
      openBoole: false,
      title: '新建收款',
      commit: '',
      types: 'create',
      customerTitle: '回款代理商名称',
      formData: {
        customerType: '',
        bankName: '',
        bankNumber: '',
        customerId: '',
        customerName: '',
        customerNumber: '',
        receiveAmount: '',
        payTime: undefined,
        headName: '',
        headId: undefined,
      },
      rules: {
        customerType: [
          {
            required: true,
            message: '请选择回款类型',
            trigger: 'change',
          },
        ],
        bankName: [
          {
            required: true,
            message: '请输入开户行名称',
            trigger: 'blur',
          },
        ],
        bankNumber: [
          {
            required: true,
            message: '请输入银行卡号',
            trigger: 'blur',
          },
        ],
        customerId: [
          {
            required: true,
            message: '请选择付款方',
            trigger: 'change',
          },
        ],
        receiveAmount: [
          {
            required: true,
            validator: receiveAmountPass,
            trigger: 'blur',
          },
        ],
        payTime: [
          {
            required: true,
            message: '请选择付款日期',
            trigger: 'change',
          },
        ],
        headId: [
          {
            required: true,
            message: '请选择负责营销职员',
            trigger: 'change',
          },
        ],
        remark: [
          {
            required: true,
            message: '请输入款项描述',
            trigger: 'blur',
          },
        ],
        normal: [],
      },
      openRef: null,
      returnTypeOption:
        crmStore.getters['dictionary/getDictionary']['returned_money_type'],
      customerTypeOption:
        crmStore.getters['dictionary/getDictionary'][
          'returned_money_customer_type'
        ],
      officeClerkOption: crmStore.getters['company/getHeadOptions'],
      customerOption: [],
      customerLoading: false,
    })
    const currentInstance = getCurrentInstance()

    const close = () => {
      reactiveData.openBoole = false
      reactiveData.openRef.clearValidate()
      reactiveData.openRef.resetFields()
    }

    const open = (dataObj) => {
      reactiveData.types = dataObj.types
      if (dataObj.types === 'create') {
        reactiveData.commit = api.returnedAndReceivable.RETURNEDMONEY_CREATE
      } else if (dataObj.types === 'edit') {
        reactiveData.title = '编辑收款'
        reactiveData.commit = api.returnedAndReceivable.RETURNEDMONEY_EDIT
        reactiveData.formData = dataObj.data
        getCustomerOption(
          reactiveData.formData.customerType,
          reactiveData.formData.customerName
        )
      }
      reactiveData.openBoole = true
    }

    const handlSubmit = () => {
      reactiveData.openRef.validate((valid) => {
        if (valid) {
          if (!reactiveData.commit) return
          reactiveData.commit(reactiveData.formData).then((res) => {
            if (res.code === 0) {
              context.emit('onSuccess')
              currentInstance.proxy.customMessage({
                type: 'success',
                message: '创建成功',
              })
              close()
            } else {
              currentInstance.proxy.customMessage({
                type: 'error',
                message: res.msg,
              })
            }
          })
        }
      })
    }
    const getCustomerLabel = (item) => {
      var label = ''
      if (reactiveData.types === 'create') {
        if (reactiveData.formData.customerType === 'agent') {
          label = item.agentName
        } else if (reactiveData.formData.customerType === 'terminal') {
          label = item.terminalName
        } else if (reactiveData.formData.customerType === 'distribute') {
          label = item.distributeName
        } else if (reactiveData.formData.customerType === 'seller') {
          label = item.sellerName
        }
      } else {
        label = reactiveData.formData.customerName
      }
      console.log(label)

      return label
    }
    const customerTypeChange = (val) => {
      console.log(val)
      reactiveData.customerOption = []
      reactiveData.formData.customerId = undefined
      reactiveData.formData.customerName = ''
    }

    const officeClerkChange = (val) => {
      var userItem = reactiveData.officeClerkOption.find((p) => p.id === val)
      if (userItem) {
        reactiveData.formData.headName = userItem.realName
      } else {
        reactiveData.formData.headName = ''
      }
    }
    const customerQuerySearch = async(queryString, cb) => {
      reactiveData.customerLoading = true
      const a = {
        module_type: reactiveData.formData.customerType,
        key_word: queryString,
      }
      let results = []
      const res = await api.terminal.CONTRACT_NAME(a)
      if (res.code === 0) {
        reactiveData.customerLoading = false
        results = res.data.list || []
        reactiveData.customerOption = results
      }
    }

    // 编辑初次打开获取option
    const getCustomerOption = (type, keyWord) => {
      const a = {
        module_type: type,
        key_word: keyWord,
      }
      api.terminal.CONTRACT_NAME(a).then((res) => {
        if (res.code === 0) {
          reactiveData.customerOption = res.data.list || []
        }
      })
    }

    const handleCustomerSelect = (val) => {
      var sel = reactiveData.customerOption.find((p) => p.id === val)
      switch (reactiveData.formData.customerType) {
        case 'agent':
          reactiveData.formData.customerName = sel.agentName
          reactiveData.formData.customerNumber = sel.agentNumber
          break
        case 'distribute':
          reactiveData.formData.customerName = sel.distributeName
          reactiveData.formData.customerNumber = sel.distributeNo
          break
        case 'terminal':
          reactiveData.formData.customerName = sel.terminalName
          reactiveData.formData.customerNumber = sel.terminalNo
          break
        case 'seller':
          reactiveData.formData.customerName = sel.sellerName
          reactiveData.formData.customerNumber = sel.sellerNumber
          break
      }
    }

    return {
      ...toRefs(reactiveData),
      close,
      open,
      handlSubmit,
      customerQuerySearch,
      handleCustomerSelect,
      customerTypeChange,
      getCustomerLabel,
      officeClerkChange,
    }
  },
}
</script>

<style scoped>
/* @import url(); 引入css类 */
</style>
